package AdamsDevice;

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import javax.swing.*;

import java.io.*;
import java.net.*;

class ClientWorker4 implements Runnable {
	private Socket client;
	private JTextArea textArea;


	ClientWorker4(Socket client, JTextArea textArea) {
		this.client = client;
		this.textArea = textArea;
	}
	public static String walkin(File dir) {
		String pattern1 = ".dat";//REPLACE with media file extension
		String pattern2 = ".txt";//REPLACE with media file extension
		String list = "";
		File listFile[] = dir.listFiles();

		if(listFile != null) {
			for(int i=0; i<listFile.length; i++) {
				if(listFile[i].isDirectory()) {
					walkin(listFile[i]);
				} else {

					if(listFile[i].getName().endsWith(pattern1)||listFile[i].getName().endsWith(pattern2)) {



						System.out.println(listFile[i].getPath());
						list =
							list+listFile[i].getPath();

					}
				}
			}
		}
		return list;
	}

	public void run(){
		String line;
		String outLine = "";
		BufferedReader in = null;
		PrintWriter out = null;
		try{
			in = new BufferedReader(new
					InputStreamReader(client.getInputStream()));
			out = new PrintWriter(client.getOutputStream(), true);
		} catch (IOException e) {
			System.out.println("in or out failed");
			System.exit(-1);
		}

		while(true){
			try{
				line = in.readLine();
				long time = System.currentTimeMillis();
				textArea.append("\n"+line);
				//Send data back to client

				System.out.println("Request received:" +time);

				if(line.equalsIgnoreCase("List")){
					
					// edit this directory, this is where the media is accessed.
					outLine=  walkin(new File("C:/mediaboom"));

					//Adam: "checks if it's a play command by splitting the message"
				}else if(line.split("->")[0].equalsIgnoreCase("play")){

					System.out.println("playing: "+ line.split("->")[1]);
					outLine = "playing->"+line.split("->")[1];
					System.out.println(outLine);
				}else if(line.split("->")[0].equalsIgnoreCase("command")){
					outLine = "running command: "+line.split("->")[1];
				}else{
					continue;
				}
				long time2 = System.currentTimeMillis();
				long timeTaken = (time2-time);
				System.out.println("Request processed in: " +timeTaken
						+"ms");
				textArea.append("\n"+line);
				textArea.append("\n"+outLine);
				out.println(outLine);
				//in.close();

			} catch (IOException e) {
				System.out.println("Read failed TestServer3 end");
				System.exit(-1);
			}
		}
	}
}

class TestServer4 extends JFrame{
	public static final String SERVICE_TYPE = "_screen_service._tcp.local.";
	public static final String SERVICE_NAME = "FUCKFACE";
	public static final int SERVICE_PORT = 1236;

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	JLabel label = new JLabel("Text received over socket:");
	JPanel panel;
	JTextArea textArea = new JTextArea();
	JScrollPane jScrollPane = new JScrollPane();
	ServerSocket server = null;
	int port = 0;

	TestServer4(int a_port){ //Begin Constructor
		port = a_port;
		panel = new JPanel();
		panel.setLayout(new BorderLayout());
		panel.setBackground(Color.white);
		getContentPane().add(panel);
		panel.add("North", label);
		panel.add("Center", textArea);
	} //End Constructor

	public void listenSocket(){
		try{
			server = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("Could not listen on port 1234");
			System.exit(-1);
		}
		while(true){
			ClientWorker4 w;
			try{
				w = new ClientWorker4(server.accept(),
						textArea);
				Thread t = new Thread(w);
				t.start();
			} catch (IOException e) {
				System.out.println("Accept failed: 1234");
				System.exit(-1);
			}
		}
	}

	protected void finalize(){
		//Objects created in run method are finalized when
		//program terminates and thread exits
		try{
			server.close();
		} catch (IOException e) {
			System.out.println("Could not close socket");
			System.exit(-1);
		}
	}

	public static void main(String[] args)throws IOException {

		JmDNS jmdns = JmDNS.create();
		ServiceInfo info = ServiceInfo.create(SERVICE_TYPE,
				SERVICE_NAME, SERVICE_PORT, 0, 0,
		"a_property=some_value");
		jmdns.registerService(info);
		System.out.println("Registered Service as " + info);

		TestServer4 frame = new TestServer4(SERVICE_PORT);
		frame.setTitle("Server Program");
		WindowListener l = new WindowAdapter() {
			public void windowClosing(WindowEvent e) {

				System.exit(0);
			}
		};
		frame.addWindowListener(l);
		frame.pack();
		frame.setVisible(true);
		frame.listenSocket();



		//The TCPSocketServer class has been modified to run as a thread
		// socket = new Thread(new TestServer3(SERVICE_PORT));

		//socket.start();
		// Wait for a keystroke before unregistering and quitting.

		//        System.out.println("Press enter to unregister and quit");
		//        new BufferedReader(new InputStreamReader(System.in)).readLine();
		//        // Unregister the service.
		//        jmdns.unregisterService(info);
		//        jmdns.close();
		//        System.exit(0);
	}}
